842E - Nikita and game - CodeForces Solution


binary search dfs and similar divide and conquer graphs trees *2800

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
const int N=3e5+5;
vector<int> s1,s2;
int n,deep[N];
int fa[N][30];
void add(int u,int fath){
	deep[u]=deep[fath]+1,fa[u][0]=fath;
    for(int i=0;fa[u][i];++i){
        fa[u][i+1]=fa[fa[u][i]][i];    
    }
}
int LCA(int u,int v){
	if(deep[u]>deep[v]) swap(u,v);
    for(int i=20;i>=0;--i){
        if(deep[u]<=deep[v]-(1<<i)){
            v=fa[v][i];    
        }    
    }
    if(u==v) return u;
    for(int i=20;i>=0;--i){
        if(fa[u][i]!=fa[v][i]){
            u=fa[u][i],v=fa[v][i];
        }
    } 
    return fa[u][0];
}
int dist(int u,int v){
	return deep[u]+deep[v]-deep[LCA(u,v)]*2+1;
}
int d;
int main(){
	scanf("%d",&n);
	add(1,0);
	s1.push_back(1);
	for(int i=2;i<=n+1;i++){
		int x;
		scanf("%d",&x);
		add(i,x);
		int d1=s1.empty()?0:dist(i,s1.front()),d2=s2.empty()?0:dist(i,s2.front());
		if(max(d1,d2)>d){
			if(d1>d2){
				d=d1;
				for(int j=0;j<(int)s2.size();j++){
					if(dist(s2[j],i)==d)s1.push_back(s2[j]);
				}
				s2.clear();
				s2.push_back(i);
			}
			else{
				d=d2;
				for(int j=0;j<(int)s1.size();j++){
					if(dist(s1[j],i)==d)s2.push_back(s1[j]);
				}
				s1.clear();
				s1.push_back(i);
			}
		}
		else if(max(d1,d2)==d){
			if(d1>d2)s2.push_back(i);
			else s1.push_back(i);
		}
		cout<<s1.size()+s2.size()<<endl;
	}
	
	return 0;
}
 	   	  	 		  		      	 					 	


Comments

Submit
0 Comments
More Questions

347. Top K Frequent Elements
1503. Last Moment Before All Ants Fall Out of a Plank
430. Flatten a Multilevel Doubly Linked List
1290. Convert Binary Number in a Linked List to Integer
1525. Number of Good Ways to Split a String
72. Edit Distance
563. Binary Tree Tilt
1306. Jump Game III
236. Lowest Common Ancestor of a Binary Tree
790. Domino and Tromino Tiling
878. Nth Magical Number
2099. Find Subsequence of Length K With the Largest Sum
1608A - Find Array
416. Partition Equal Subset Sum
1446. Consecutive Characters
1618A - Polycarp and Sums of Subsequences
1618B - Missing Bigram
938. Range Sum of BST
147. Insertion Sort List
310. Minimum Height Trees
2110. Number of Smooth Descent Periods of a Stock
2109. Adding Spaces to a String
2108. Find First Palindromic String in the Array
394. Decode String
902. Numbers At Most N Given Digit Set
221. Maximal Square
1200. Minimum Absolute Difference
1619B - Squares and Cubes
1619A - Square String
1629B - GCD Arrays